<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.workstation" placeholder="请选择车间" clearable style="width: 200px" class="filter-item">
        <el-option v-for="item in selectOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-date-picker
      v-model="listQuery.datetime"
      type="daterange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      class="filter-item"
      @change="dateChange">
    </el-date-picker>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-waves class="filter-item" type="info" icon="el-icon-refresh" @click="handleReset">
        重置
      </el-button>
    </div>
    <el-row>
      <div ref="chart" class="chart" :style="chartStyle" />
    </el-row>
  </div>
</template>
<script>
import echarts from 'echarts'
import resize from '../mixins/resize'
import { fetchMonthList } from '@/api/bdc/output-chart'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import { getMonthDays } from '@/utils/dateutils'
const selectOptions = [
  { key: 'HZ11_20', label: '焊装车间' },
  { key: 'TZ11_20', label: '涂装车间' },
  { key: 'ZZ11_30', label: '总装车间' }
]
const animationDuration = 3000
export default {
  name: 'MonthlyOutputChart',
  directives: { waves },
  mixins: [resize],
  data() {
    return {
      // 查询模块
      listQuery: {
        workstation: undefined,
        datetime: null
      },
      selectOptions: selectOptions,
      // echarts
      chart: null,
      chartData: null,
      chartStyle: {height: '500px', width: '100%'},
    }
  },
  mounted() {
    // 初始化echarts容器
    this.$nextTick(() => {
      this.chart = echarts.init(this.$refs.chart)
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    // 日期范围限制及图表x轴数据生成
    dateChange(date) {
      if (date) {
        const startDate = date[0]
        const endDate = date[1]
        if (endDate.valueOf() - startDate.valueOf() > 60 * 24 * 60 * 60 * 1000) {
          this.$message.warning('时间范围超过了60天，请重新选择！')
          this.listQuery.datetime = null
          return
        }
      }
    },
    // 查询
    handleFilter() {
      // 验证
      if (!this.listQuery.workstation) {
        this.$message.warning('请选择车间！')
        return
      }
      if (this.listQuery.datetime === null) {
        this.$message.warning('请输入时间范围！')
        return
      }
      const data = {
        codeValue: this.listQuery.workstation,
        beginDate: parseTime(this.listQuery.datetime[0], '{y}-{m}-{d}'),
        endDate: parseTime(this.listQuery.datetime[1], '{y}-{m}-{d}')
      }
      fetchMonthList(data).then(res => {
        if (res.code == 200) {
          this.initChart()
          for (const i of res.data) {
            this.chartData.xAxisData.push(i.NEWDAY)
            this.chartData.series.push(i.TOTAL)
          }
          this.setOptions(this.chartData)
        } else {
          this.$message.error('服务器内部错误！');
        }
      })
    },
    // 重置
    handleReset() {
      this.listQuery = {
        workstation: undefined,
        datetime: null
      }
    },
    // 初始化echarts数据
    initChart() {
      this.chartData = {
        xAxisData: [],
        series:[]
      }
    },
    setOptions({ xAxisData, series } = {}) {
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        xAxis: [{
          type: 'category',
          data: xAxisData,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            rotate: 45
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          },
          max: 25
        }],
        series: [{
          name: '产量',
          type: 'bar',
          stack: 'vistors',
          barWidth: '60%',
          data: series,
          animationDuration,
          itemStyle: {
            normal: {
              color: (params) => {
                let color;
                params.data < 20 ? color =  'red' : color = 'green';
                return color;
              },
              lineStyle: {
                color: 'green',
              },
              // 显示点值
              label: {
                show: true,
                position: 'top'
              }
            }
          },
          // 显示辅助线
          markLine:{
            /*以下设置一行后，平均线就没有开始和结束标记了（即看不见箭头了）*/
            symbol:"none",
            data: [
              {
                name: 'Y 轴值为 200 的水平线',
                yAxis: 20,
                lineStyle:{
                  normal:{
                    color:"red",
                    width:2,
                    type:"solid"
                  }
                }
              }
            ]
          },
        }]
      })
    }
  }
}
</script>